import { useComp } from '@/hooks'
import { onMounted, computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElButton } from 'element-plus'
import { useRef } from '@/hooks/store'
import { ANY_DATA_TYPE } from '@/type'

const global: ANY_DATA_TYPE = reactive({})
function useGlobal <T> (key: string, value: T) {
  const newKey = key.toString()
  if (!global[newKey]) {
    global[newKey] = value
  }
  const reunst = ref(global[newKey])
  const update = (val: T) => {
    global[newKey] = val
    reunst.value = val
  }
  return [reunst, update]
}
function CustomFunctionTsx () {
  const [num, setNum] = useGlobal('num', 0)
  return <ElButton onClick={() => setNum(num.value + 1)}>自定义tsx {num.value}</ElButton>
}
function CustomFunctionTsx2 () {
  const [num, setNum] = useRef<number>(0, CustomFunctionTsx2.toString())
  return <ElButton onClick={() => setNum(num.value + 1)}>自定义tsx {num.value}</ElButton>
}

export default useComp(() => {
  const store = useStore()

  const count2 = computed(() => store.state.base.count)
  const type = 'base/count'
  const key = type.split('/')
  const state = computed(() => {
    let result = store.state[key[0]]
    for (let i = 1; i < key.length; i++) {
      result = result[key[i]]
    }
    return result
  })
  const commit = (value: number) => {
    store.commit('base/update', { count: value })
  }
  onMounted(() => {
    console.log('home mounted')
  })
  return () => (
    <div>
      <div>你好</div>
      <ElButton onClick={() => commit(store.state.base.count + 1)}>按钮（+）</ElButton>
      <h1>{store.state.base.count}</h1>
      <ElButton onClick={() => store.commit('update', { abc: store.state.abc + 1 })}>按钮（+）</ElButton>
      <h1>{store.state.abc}</h1>
      <h1>{count2.value}</h1>
      <h1>{state.value}</h1>
      <CustomFunctionTsx></CustomFunctionTsx>
      <CustomFunctionTsx2></CustomFunctionTsx2>
    </div>
  )
})
